<template>
  <a-modal
    style="width: 50%"
    :title="titleMap[mode]"
    :visible="visible"
    :confirm-loading="confirmLoading"
    :destroyOnClose="true"
    @cancel="handleCancel"
    :maskClosable="false"
    :forceRender="true">
    <div style="margin-top: 12px;">
      <a-form-model ref="ruleAddForm" :model="addForm" :rules="addRules">
        <a-form-model-item label="姓名" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
          <a-input placeholder="请输入姓名" v-model.trim="addForm.name" />
        </a-form-model-item>
        <a-form-model-item label="组织单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="organizationUnitId">
          <a-tree-select
            v-model="addForm.organizationUnitId"
            style="width: 100%"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            tree-default-expand-all
            :tree-data="treeData"
            :max-tag-count="10"
            placeholder="请选择组织单位"
            :replaceFields="replaceFields"
            tree-node-filter-prop="organizationUnitName"
            :default-expanded-keys="Ids"
            :default-selected-keys="Ids"
            @change="orgChange">
          </a-tree-select>
        </a-form-model-item>
        <a-form-model-item
          label="是否开通"
          v-if="mode == 'add'"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          prop="needAccount">
          <a-radio-group @change="radioChange" v-model="addForm.needAccount">
            <a-radio :value="true">是</a-radio>
            <a-radio :value="false">否</a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item
          label="角色"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          v-if="mode == 'add'"
          prop="roleIds"
          :rules="[{ required: radioValue, trigger: 'change', message: '请选择角色!' }]">
          <!-- <a-select mode="multiple" labelInValue placeholder="请选择角色" @change="roleChange"
                        v-model="addForm.roleIds" :defaultFirstOption="addForm.roleIds">
                        <a-select-option v-for="item in roleList" :key="item.roleId" :value="item.roleId">
                            {{ item.name }}
                        </a-select-option>
                    </a-select> -->
          <a-tree-select
            :replaceFields="{
              children: 'children', label: 'name', value: 'roleId', key: 'roleId'
            }"
            :default-expanded-keys="addForm.roleIds"
            :default-selected-keys="addForm.roleIds"
            :dropdown-style="{ maxHeight: '200px', overflow: 'auto' }"
            tree-checkable
            tree-default-expand-all
            :tree-data="roleList"
            :max-tag-count="10"
            tree-node-filter-prop="name"
            placeholder="请选择角色"
            v-model="addForm.roleIds"
            @change="roleChange">
          </a-tree-select>
        </a-form-model-item>
        <a-form-model-item
          label="邮箱"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          prop="email"
          :rules="[{ required: radioValue, trigger: 'blur', validator: verifyEmail }]">
          <a-input placeholder="请输入邮箱" v-model="addForm.email" />
        </a-form-model-item>
        <a-form-model-item
          label="密码"
          v-if="mode == 'add'"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          prop="password"
          :rules="[{ required: radioValue, trigger: 'blur', validator: verifyPassword }]">
          <!-- <a-input placeholder="请输入密码" v-model.trim="addForm.password" /> -->
          <a-input-password placeholder="请输入密码" v-model.trim="addForm.password" type="text" />
        </a-form-model-item>
        <a-form-model-item label="手机号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="phoneNumber">
          <a-input placeholder="请输入手机号" v-model.trim="addForm.phoneNumber" :max-length="11"/>
        </a-form-model-item>
        <a-form-model-item label="身份证号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="identityCardId">
          <a-input placeholder="请输入身份证号" v-model.trim="addForm.identityCardId" />
        </a-form-model-item>

        <a-form-model-item label="头衔" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="presentTitle">
          <a-input placeholder="请输入头衔" v-model.trim="addForm.presentTitle" />
        </a-form-model-item>
      </a-form-model>
    </div>
    <template slot="footer">
      <a-button key="back" @click="handleCancel">
        关闭
      </a-button>
      <a-button type="primary" :visible="visibleBtn" :loading="loadingBtn" @click="handleOk" >
        保存
      </a-button>
    </template>
  </a-modal>
</template>
<script>
import { getOrg } from '@/api/org'
import { getRoles } from '@/api/lessee'
import { addEmployees, editEmployees, detailEmployees } from '@/api/staff'
// import { verifyPassword, verifyPhone, verifyEmail } from '@/utils/verificate'
export default {
    components: {},
    data () {
        return {
            // verifyEmail,
            addRules: {
                name: [
                    { required: true, message: '请输入姓名!', trigger: 'blur' }
                ],
                organizationUnitId: [
                    { required: true, message: '请选择组织单位!', trigger: 'change' }
                ],
                needAccount: [
                    { required: true, message: '请选择是否开通!', trigger: 'change' }
                ]
                // phoneNumber: [
                //     { required: this.radioValue, message: '请输入手机号!', trigger: 'change' }
                //     // ,{validator: verifyPhone}
                // ],
                // roleIds: [
                //     { required: true, message: '请选择角色!', trigger: 'change' }
                // ],
            },
            addForm: {
                organizationUnitId: undefined,
                name: '',
                identityCardId: '',
                presentTitle: '',
                phoneNumber: '',
                email: '',
                needAccount: false,
                password: '',
                roleIds: []

            },
            labelCol: {
                xs: { span: 24 },
                sm: { span: 5 }
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 16 }
            },
            radioValue: false,
            treeData: [], // 组织单位
            roleList: [], // 租户角色
            Ids: null,
            replaceFields: { children: 'children', label: 'organizationUnitName', value: 'organizationUnitId', key: 'organizationUnitId' },

            visible: false,
            confirmLoading: false,
            loading: false,
            visibleBtn: false,
            loadingBtn: false,
            mode: 'add',
            titleMap: {
                add: '新增',
                edit: '编辑'
            },
            rowData: ''
        }
    },
    mounted () {
        this.allApi()
    },
    methods: {
        // 组织选择
        orgChange (checkedKeys) {
            this.Ids = checkedKeys
            this.addForm.organizationUnitId = checkedKeys
        },
        verifyEmail (rule, value, callback) {
            if (!this.radioValue) return callback()
            var reg = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/
            if (value == '' || value == null) {
                return callback(new Error('请输入邮箱'))
            } else if (!reg.test(value)) {
                return callback(new Error('邮箱格式不正确'))
            }
            callback()
        },

        // 验证手机号
        verifyPhone (rule, value, callback) {
            const reg = /^[1][3, 4, 5, 6, 7, 8, 9][0-9]{9}$/
            if (!this.radioValue) return callback()
            if (value == '' || value == null) {
                return callback(new Error('请输入手机号'))
            } else if (!reg.test(value)) {
                return callback(new Error('您输入的手机号码格式错误'))
            }
            callback()
        },
        // 验证密码
        verifyPassword (rule, value, callback) {
            if (!this.radioValue) return callback()
            var reg = /^[^\u4e00-\u9fa5]+$/ // 使用正则表达式匹配非中文字符
            if (value == '' || value == null) {
                return callback(new Error('请输入密码'))
            } else if (!reg.test(value)) {
                return callback(new Error('密码不能为中文'))
            }
            callback()
        },
        allApi () {
            getOrg().then(res => {
                if (res.code == 200) {
                    this.treeData = res.data
                }
            })
            getRoles().then(res => {
                if (res.code == 200) {
                    this.roleList = res.data
                }
            })
        },
        // 角色选择
        roleChange (e) {
            this.addForm.roleIds = e
        },
        // 是否开通单选框切换
        radioChange (e) {
            const { value } = e.target
            this.radioValue = value
            this.addForm.needAccount = value
        },
        // 显示
        open (mode = 'add') {
            this.mode = mode
            this.visible = true
            return this
        },
        // 获取行数据和id
        setData (row) {
            console.log(row)
            this.rowData = row
            // this.addForm.organizationUnitId = this.rowData.organizationUnitId+''
            if (this.mode == 'edit') {
                this.radioValue = false
                detailEmployees(row.partyId).then(res => {
                    if (res.code == 200) {
                        this.addForm = res.data
                        this.addForm.identityCardId = ''
                        if (this.rowData.organizationUnitId == null) {
                            this.addForm.organizationUnitId = undefined
                        } else {
                            this.addForm.organizationUnitId = this.rowData.organizationUnitId
                        }
                    }
                })
            }
        },
        // 关闭
        handleCancel () {
            this.visible = false
            this.loadingBtn = false
            this.visibleBtn = false
            this.$emit('close')
        },
        // 确认
        handleOk () {
            this.loadingBtn = true
            this.visibleBtn = true
            this.$refs.ruleAddForm.validate(valid => {
                if (valid) {
                    // let CardId = this.addForm.identityCardId
                    // console.log(this.addForm)
                    // if(!this.verifyCardId(CardId)) return
                    const Api = this.mode == 'add' ? addEmployees : editEmployees
                    if (this.mode == 'edit') {
                        delete this.addForm.needAccount
                        delete this.addForm.roleIds
                        delete this.addForm.roleIds
                        delete this.addForm.password
                    }
                    Api(this.addForm).then(res => {
                        if (res.code === 200) {
                            this.$notification['success']({
                                message: '提示',
                                description: '保存成功！',
                                duration: 8
                            })
                            this.visible = false
                            this.$emit('success')
                        } else {
                            this.$notification['error']({
                                message: '提示',
                                description: res.message,
                                duration: 8
                            })
                        }
                        this.visibleBtn = false
                        this.loadingBtn = false
                    })
                } else {
                    this.loadingBtn = false
                    this.visibleBtn = false
                    return false
                }
            })
        }
    }
}
</script>
<style scoped lang="less" ></style>
